package com.longge;

public class ConstructMaximumBinaryTreeII {

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return buildTree(nums, 0, nums.length);

    }

    private TreeNode buildTree(int[] nums, int start, int end) {
        if (start >= end) return null;
        int maxIndex = getMaxIndex(nums, start, end);
        TreeNode root = new TreeNode(nums[maxIndex]);
        root.left = buildTree(nums, start, maxIndex);
        root.right = buildTree(nums, maxIndex + 1, end);
        return root;
    }

    int getMaxIndex(int[] nums, int start, int end) {
        int max = Integer.MIN_VALUE, index = -1;
        for (int i = start; i < end; i++) {
            if (nums[i] >= max) {
                max = nums[i];
                index = i;
            }
        }
        return index;
    }
}
